<!-- 选择弹出窗 -->
<template>
	<div>
		<el-dialog :title="state.title" v-model="state.isShowDialog"  center class="borderRadius10" width="1420">
			<div class="cropper-warp">
				<!-- <el-table :data="state.goodList" border style="width: 100%;">
                    <el-table-column label="编码" width="90" align="center">
						<template #default="scope">
							<span>{{ scope.row.data.skuId }}</span>
						</template>
					</el-table-column>
					<el-table-column label="图片" align="center">
						<template #default="scope">
							<div style="display: flex;justify-content:center;align-items: center;">
								<el-image style="width:32px;height: 32px;" :src="scope.row.data.imgUrl" fit="cover" />
							</div>
						</template>
					</el-table-column>
					<el-table-column label="商品名称"  align="center">
						<template #default="scope">
							<span> {{ scope.row.data.spuName }} </span>
						</template>
					</el-table-column>
					<el-table-column label="类型"  align="center">
						<template #default="scope">
							<span>{{ scope.row.data.sku.skuTypeName }}</span>
						</template>
					</el-table-column>
					<el-table-column label="零售价"  align="center">
						<template #default="scope">
							<span>{{ scope.row.data.sku.retailPrice }}</span>
						</template>
					</el-table-column>
					<el-table-column label="折扣比例" v-if="state.type == 'discountSku' || state.type == 'handselDiscountSku'" align="center">
						<template #default="scope">
							<el-input  placeholder="请输入" />
						</template>
					</el-table-column>
					<el-table-column label="关联数量" v-if="state.type == 'relatedSku'" align="center">
						<template #default="scope">
							<el-input placeholder="请输入" v-model="scope.row.itemNum"/>
						</template>
					</el-table-column>
					<el-table-column label="活动价" v-if="state.type == 'relatedSku'" align="center">
						<template #default="scope">
							<el-input  placeholder="请输入" />
						</template>
					</el-table-column>
					<el-table-column label="单次服务用量" v-if="state.type == 'cardRelatedSku'" align="center">
						<template #default="scope">
							<el-input placeholder="请输入" v-model="scope.row.itemNum"/>
						</template>
					</el-table-column>
                    
                </el-table> -->
				<el-table v-if="state.showType == 0" v-loading="state.loading" row-key="setId"  :data="state.goodList" ref="goodSpuTableRef"
					@select-all="handleSelectionChange" @select="secectItemFun">
					<el-table-column type="expand" width="1">
						<template #default="props">
							<section v-if="props.row.isShowSkuList">
								<expandSkuMsg ref="expandSkuMsgRef" :setId="props.row.setId" @refreshFun="getGoodsList"
								 :selectIdData=state.selectIdData :skuTableData="props.row.skuList"></expandSkuMsg>
							</section>
							<section class="ml80 mr80" v-if="props.row.isShowSpuMsg">
								<el-row>
									<el-col :span="5" class="mb10">
										<span>操作人：{{ props.row.updateBy }}</span>
									</el-col>
									<el-col :span="5" class="mb10">
										<span>创建人：{{ props.row.createdBy }}</span>
									</el-col>
									<el-col :span="5" class="mb10">
										<span>操作时间：{{ props.row.updateTime }}</span>
									</el-col>
									<el-col :span="5" class="mb10">
										<span>创建时间：{{ props.row.createdTime }}</span>
									</el-col>
								</el-row>
							</section>
						</template>
					</el-table-column>
					<el-table-column label="" width="20">
						<template #default="scope">
							<el-icon title="展开商品其他信息" @click="expandSpuMsg(scope.row)">
								<ele-CaretRight v-if="!scope.row.isShowSpuMsg"/>
								<ele-CaretBottom v-if="scope.row.isShowSpuMsg"  />
							</el-icon>
						</template>
					</el-table-column>
					<el-table-column type="selection" width="30" :reserve-selection=true />
					<el-table-column label="SPU" width="90" >
						<template #default="scope">
							<span>{{ scope.row.data.spuId }}</span>
						</template>
					</el-table-column>
					<el-table-column label="图片" width="90">
						<template #default="scope">
							<div style="display: flex;justify-content:flex-start;align-items: center;">
								<el-icon title="展开商品Sku"  @click="expandSkuList(scope.row)">
									<ele-Plus v-if="!scope.row.isShowSkuList"/>
									<ele-Minus v-if="scope.row.isShowSkuList"/>
								</el-icon>
								<el-image class="borderRadius5 ml5 mr20" style="width:32px; height: 32px;" :src="scope.row.data.imgUrl"
									fit="cover" />
							</div>
						</template>
					</el-table-column>
					<el-table-column label="品牌"  >
						<template #default="scope">
							<span>{{ scope.row.data.brandIdName }}</span>
						</template>
					</el-table-column>
					<el-table-column label="商品名称" width="380" class-name="aaaa">
						<template #default="scope">
							<span class="ellipsis2">{{ scope.row.data.spuName }}</span>
						</template>
					</el-table-column>
					<el-table-column label="零售价" >
						<template #default="scope">
							<span style="display: flex;align-items: center;"> ￥{{ scope.row.data.priceRange }}&nbsp;
								<el-icon class="iconfont-warp-value"> <ele-Edit /> </el-icon> 
							</span>
						</template>
					</el-table-column>
					
					<el-table-column label="销售渠道">
						<template #default="scope">
							<span>{{ scope.row.data.salesChannelName }}</span>
						</template>
					</el-table-column>
					<el-table-column label="来源">
						<template #default="scope">
							<span>{{ scope.row.data.sourceName }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="title" label="操作" width="120" show-overflow-tooltip>
						<template #default="scope">
							<el-button text type="primary" @click="delItem('spu',scope.row)">
								移除
							</el-button>
						</template>
					</el-table-column>
					<template #empty>
                        <el-empty description="暂无数据" />
                    </template>
				</el-table>
				<el-table v-if="state.showType == 1" v-loading="state.loading" :data="state.goodList" row-key="setId" 
							ref="goodSkuTableRef" @selection-change="skuSelectionChangeFun">
					<el-table-column type="expand" width="1">
						<template #default="props">
							<section class="ml80 mr80" v-if="props.row.isShowSkuMsg">
								<el-row>
									<el-col :span="5" class="mb10">
										<span>操作人：{{ props.row.updateBy }}</span>
									</el-col>
									<el-col :span="5" class="mb10">
										<span>创建人：{{ props.row.createdBy }}</span>
									</el-col>
									<el-col :span="5" class="mb10">
										<span>操作时间：{{ props.row.updateTime }}</span>
									</el-col>
									<el-col :span="5" class="mb10">
										<span>创建时间：{{ props.row.createdTime }}</span>
									</el-col>
								</el-row>
							</section>
						</template>
					</el-table-column>
					<el-table-column label="" width="20" >
						<template #default="scope">
							<el-icon title="展开商品其它信息"  @click="expandSkuMsgFun(scope.row)">
								<ele-CaretRight v-if="!scope.row.isShowSkuMsg"/>
								<ele-CaretBottom v-else-if="scope.row.isShowSkuMsg"  />
							</el-icon>
						</template>
					</el-table-column>
					<el-table-column type="selection" width="30" :reserve-selection=true />
					<el-table-column label="SKU" width="90"  >
						<template #default="scope">
							<span>{{ scope.row.data.skuId }}</span>
						</template>
					</el-table-column>
					<el-table-column label="图片" width="90">
						<template #default="scope">
							<div style="display: flex;justify-content:center;align-items: center;">
								<el-image style="width:32px;height: 32px;" :src="scope.row.data.imgUrl" fit="cover" />
							</div>
						</template>
					</el-table-column>
					<el-table-column label="品牌"  >
						<template #default="scope">
							<span> {{ scope.row.data.brandIdName }}</span>
						</template>
					</el-table-column>
					<el-table-column label="商品名称" width="380" class-name="aaaa">
						<template #default="scope">
							<span> {{ scope.row.data.spuName }} {{ scope.row.data.skuSerialName }}</span>
						</template>
					</el-table-column>
					<el-table-column label="属性">
						<template #default="scope">
							<span>{{ scope.row.data.skuTypeName }}</span>
						</template>
					</el-table-column>
					<el-table-column label="规格">
						<template #default="scope">
							<span>{{ scope.row.data.skuSerialName }}</span>
						</template>
					</el-table-column>
					<el-table-column label="零售价">
						<template #default="scope">
							<span>{{ scope.row.data.retailPrice }}元</span>
						</template>
					</el-table-column>
					<el-table-column label="来源">
						<template #default="scope">
							<span>{{ scope.row.data.sourceName }}</span>
						</template>
					</el-table-column>
					<el-table-column label="销售渠道">
						<template #default="scope">
							<span>{{ scope.row.data.salesChannelName }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="title" label="操作" width="120" show-overflow-tooltip>
						<template #default="scope">
							<el-button text type="primary" @click="delItem('sku',scope.row)">
								移除
							</el-button>
						</template>
					</el-table-column>
					<template #empty>
                        <el-empty description="暂无数据" />
                    </template>
				</el-table>
				<el-row justify="end">
					<el-col :span="24" class="flex-end-center">
						<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
							:pager-count="5" :page-sizes="[10, 20, 30]" v-model:current-page="state.param.pageNum" background
							v-model:page-size="state.param.pageSize" layout="total, sizes, prev, pager, next, jumper"
							:total="state.total">
						</el-pagination>
					</el-col>
				</el-row>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel"  >取 消</el-button>
					<el-button type="primary" @click="addGoodsFile()"> 
						<el-icon> <ele-Plus /> </el-icon> 添加商品
					</el-button>
					<el-button type="primary" @click="batchDelete()"> 
						<el-icon> <ele-Delete /> </el-icon> 批量删除
					</el-button>
					<el-button type="primary" @click="clearGoods()"> 
						<el-icon> <ele-Delete /> </el-icon> 清空关联商品
					</el-button>
					<el-button type="primary" @click="onSubmit"  >确 认</el-button>
				</span>
			</template>
		</el-dialog>
		<goodSelectDialog  @goodsSubmitFun="goodsSubmitFun" ref="goodSelectDialogRef" />
	</div>
</template>

<script setup lang="ts" name="cropper">
import { reactive, ref, defineAsyncComponent, watch } from 'vue';
import { goodsOperate,goodsRemove } from '/@/api/commodity';
import { ElMessageBox, ElMessage, ElTable } from 'element-plus';
// 引入组件
const expandSkuMsg = defineAsyncComponent(() => import('/@/components/dialog/expandSkuMsgTwo.vue'));
const goodSelectDialog = defineAsyncComponent(() => import('/@/components/dialog/newGoodsSelects.vue'));
// 定义变量内容
const expandSkuMsgRef = ref();
const goodSelectDialogRef = ref();
const goodSpuTableRef = ref<InstanceType<typeof ElTable>>();
const emit = defineEmits(['selectItemFun'])
// 定义变量内容
const state = reactive({
	dictType:null,
	selectId:0,
	showType:0,
    loading: false,
	isShowDialog: false,
    title:'',
	cropperImgBase64: '',
    param: {
		type : 1,
		keyWord: "",
		pageNum: 1,
		pageSize: 10,  
	},
	query:{
		searchType: [
			{ value: 1, label: 'SPU查询' },
			{ value: 1, label: 'SKU查询' }
		]
	},
    total: 0,
	type: '',
	goodList:[] as Array<any>,
	// 选中的spu数据
	selectIdData:[] as Array<any>,
	// 选中的sku数据
	selectSkuIdData:[]
});

// 打开弹窗
const openDialog = async (type: string,data: any) => {
	if(data != '[]' && data.length > 0){
		state.dictType = data[0].dictType;
	}else{
		state.dictType = null;
	}
	state.goodList = [];
	state.type = type;
	if(type == 'useSku' ){
		state.title ="关联可使用商品"
		state.selectId = 0;
	}else if(type == 'discountSku' ){
		state.title ="关联可使用折扣商品"
		state.selectId = 2;
	}else if(type == 'handselUseSku' ){
		state.title ="赠金关联可使用商品"
		state.selectId = 3;
	}else if(type == 'handselDiscountSku' ){
		state.title ="赠金关联可使用折扣商品"
		state.selectId = 4;
	}else if(type == 'relatedSku' ){
		state.title ="活动关联商品"
		state.selectId = 0;
	}else if(type == 'cardRelatedSku' ){
		state.title ="卡项关联商品"
		state.selectId = 0;
	}else if(type == 'goodsRelatedSku' ){
		state.title ="商品关联商品",
		state.selectId = 0;
	}
	state.isShowDialog = true;
	getGoodsList()
};

watch(() => state.selectIdData, () => { 
	setTimeout(() => {
		state.goodList.forEach((item:any) => {
			if (state.selectIdData.find(itemx => itemx.spuId === item.setId)) {
				// 把判断出来的默认表格数据push到创建的数组中
				goodSpuTableRef.value!.toggleRowSelection(item, true)
			}else{
				goodSpuTableRef.value!.toggleRowSelection(item, false)
			}
		});
	}, 100);},
    {
        deep: true,
        immediate: true
    }
);

// spu选中
const handleSelectionChange = (val:any) => {
	if(val.length == 0){
		state.selectIdData = [];
	}else{
		let aaa: { spuId: any; skuId: any; }[] = []
		val.forEach((item:any) => {
			let skuIDlist = item.skuList.map((item: { setId: any; }) => item.setId);
			aaa.push({
				spuId: item.setId,
				skuId: skuIDlist
			})
		});
		state.selectIdData = aaa
	}
};

const secectItemFun = (selection:any, row:any) => {
	const selected = selection.some((s: any) => s == row);
	if (selected) {
		let skuIDlist = row.skuList.map((item: { setId: any; }) => item.setId); 
		state.selectIdData.push({
			spuId: row.setId,
			skuId: skuIDlist
		})
		// 选中
		console.log('勾选行：', row);
	} else {
		state.selectIdData = state.selectIdData.filter(function(item) {  
			return item.setId !== row.setId; // 保留 id 不等于 3 的对象  
		});
		// 取消选中
		console.log('取消勾选行：', row);
	}
};


// 点击spu其他信息
const expandSpuMsg = (row?: any) => {
	// expand 展开
	if(row.isShowSpuMsg){
		// sku相关信息表展开状态
		row.isShowSpuMsg = false;
		goodSpuTableRef.value.toggleRowExpansion(row);
	}else{ // 未打开
		// msg 展开时关闭sku	
		row.isShowSpuMsg = true;
		if(row.isShowSkuList){
			row.isShowSkuList = false;
		}else{
			goodSpuTableRef.value.toggleRowExpansion(row);
		}
	}
};

// 展开商品sku列表点击sku列表
const expandSkuList = async (row: any) => {
	// 当前expand信息展开状态时 且sku列表展开时直接关闭expand
	if(row.isShowSkuList){
		row.isShowSkuList = false;
		goodSpuTableRef.value.toggleRowExpansion(row);
	}else{
		// sku 展开时关闭msg	
		row.isShowSkuList = true;
		if(row.isShowSpuMsg){
			row.isShowSpuMsg = false;
		}else{
			goodSpuTableRef.value.toggleRowExpansion(row);
		}
	}
};

// 批量删除
const batchDelete = async () => {
	// const { results } = await goodsRemove({setIds:setID});
	// spu选择模式
	if(state.selectIdData.length == 0){
		return ElMessage.warning('请先选择商品');
	}
	if(state.showType == 0){
		if(state.selectIdData.length > 0){
			let setID = [] as Array<any>;
			state.selectIdData.map((item:any)=>{
				setID.push(item.spuId);
				setID = [...setID, ...item.skuId]; 
			})
			ElMessageBox.confirm( '是否移除选中关联商品?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then( async () => {
				let results = await goodsRemove({setIds:setID});
				ElMessage.success('删除成功');
			}).catch(() => {
			})
		}
	// sku选择模式
	}else if(state.showType == 1){
		if(state.selectSkuIdData.length > 0){
			ElMessageBox.confirm( '是否移除选中关联商品?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then( async () => {
				let results = await goodsRemove({setIds:state.selectIdData});
				ElMessage.success('删除成功');
				getGoodsList();
			}).catch(() => {
			})
		}
	}
}

// 清空关联商品
const clearGoods = async () => {

	// const { results } = await goodsRemove({setIds:setID});
	// 	getGoodsList(
}



// 添加视频文件
const addGoodsFile = () => {
	// console.log(informationVisibel.value)
	let type = null;
	if(state.goodList.length > 0){
		type = state.showType;
	}
	goodSelectDialogRef.value.openDialog(type);
}

// 分页点击条数
const onHandleSizeChange = (val: number) => {
	state.param.pageSize = val;
    getGoodsList();
};

// 分页点击
const onHandleCurrentChange = (val: number) => {
	state.param.pageNum = val;
    getGoodsList();
};

const getGoodsList = async () =>{
	let params = {
		selectId:state.selectId,
		dictType: state.dictType,
		pageNum: state.param.pageNum,
		pageSize: state.param.pageSize,
	}
	const { results,dictType } = await goodsOperate(params);
	if(state.showType == 0){
		state.goodList = results.records.map((obj: any) => ({  
			...obj,
			isExpand:false,
			isShowSpuMsg:false, 
			isShowSkuList:false,  
		}));
	}else if(state.showType == 1){
		state.goodList = results.records.map((obj: any) => ({  
			...obj,
			isShowSkuMsg:false,
		}));
	}
	console.log(state.goodList.length )
	state.dictType = dictType;
	state.loading = false;
	state.total = results.total;
}

// 单点删除
const delItem = async (str:string,obj:any) => {
	if(str == 'spu'){
		let setID = [];
		setID.push(obj.setId)
		obj.skuList.map((item:any,index:number)=>{
			if(index == 1){
				setID.push(item.setId)
			}
		})
		const { results } = await goodsRemove({setIds:setID});
		getGoodsList()
	}
}

// 关闭弹窗
const closeDialog = () => {
	state.isShowDialog = false;
};

// 取消
const onCancel = () => {
	closeDialog();
};

const onSubmit = () =>{
	emit('selectItemFun', state.type,state.dictType);
	closeDialog();
}

// 选中关联商品
const goodsSubmitFun = async (list: any,type: number) =>{
	if(list.length > 0){
		state.showType = type;
		if(type == 0){
			let addGoods = list.map((item: any) => { return { dictType: state.dictType,setSpuId: item.spuId, setSkuId: item.skuId,goodsType:type }})
			const { results } = await goodsOperate({selectId:state.selectId,dictType: state.dictType,addGoods:addGoods,goodsType:type});
			state.total = results.total;
			state.goodList = results.records;
		}else{
			let addGoods = list.map((item: any) => { return { dictType: state.dictType,setSkuId: item,goodsType:type }})
			const { results } = await goodsOperate({selectId:state.selectId,dictType: state.dictType,addGoods:addGoods,goodsType:type});
			state.total = results.total;
			state.goodList = results.records;
		}
	}
}


// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">

.pageQueryBoxArea{
	:deep(.el-select){
		.el-input {
			width: 160px !important;
			height: 38px;
			line-height: 38px;
		}
	}
}

.singleChoice{
	:deep(.el-table th.el-table__cell:nth-child(1) .cell ){
		visibility: hidden;
	}
}

.el-form .el-form-item:last-of-type {
    margin-bottom: 18px !important;
}

// 隐藏expand 箭头
:deep(.el-table__expand-column){
    visibility: hidden;
}

:deep(.el-card__body){
	padding-top: 0px !important;
}

.pageContentArea{
	:deep(.el-card__body){
		padding-top: 10px;
		display: flex;
		flex-direction: column;
		flex: 1;
		height: inherit;
		.el-tabs{
			.el-tabs__header{
				margin-bottom: 0;
			}
		}
		.el-table{
			flex: 1;
			.el-table__inner-wrapper::before{
				background: none !important;
			}
			.iconfont-warp-value {
				&:hover {
					color: var(--el-color-primary);
					transition: all 0.2s ease;
				}
			}
			// &:hover {
			// 	box-shadow: 0 2px 12px var(--next-color-dark-hover);
			// 	cursor: pointer;
			// 	transition: all 0.3s ease;
			// 	.iconfont-warp-value {
			// 		i {
			// 			color: var(--el-color-primary);
			// 			transition: all 0.3s ease;
			// 		}
			// 	}
			// 	.iconfont-warp-label {
			// 		color: var(--el-color-primary);
			// 		transition: all 0.3s ease;
			// 	}
			// }
		
		}
		.contentMenuBox{
			.el-dropdown{
				.el-icon{
					margin-right: 0px !important;
				}
			}
		}
	}

	// 隐藏expand 箭头
	:deep(.el-table__expand-column){
		visibility: hidden;
	}
	:deep(.el-table .aaaa .cell ){
		justify-content: left;
		padding-left: 5px;
	}
}


// dsasa
// 隐藏expand 箭头
:deep(.el-dialog){
	display: flex;
	flex-direction: column;
	margin: 0 !important;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	min-height: calc(50% - 30px);
}
.cropper-warp {
	.cropper-warp-left {
		position: relative;
		display: inline-block;
		height: 350px;
		flex: 1;
		border: 1px solid var(--el-border-color);
		background: var(--el-color-white);
		overflow: hidden;
		background-repeat: no-repeat;
		cursor: move;
		border-radius: var(--el-border-radius-base);
		.cropper-warp-left-img {
			width: 100%;
			height: 100%;
		}
	}
	.cropper-warp-right {
		width: 150px;
		height: 350px;
		.cropper-warp-right-title {
			text-align: center;
			height: 20px;
			line-height: 20px;
		}
		.cropper-warp-right-item {
			margin: 15px 0;
			.cropper-warp-right-value {
				display: flex;
				.cropper-warp-right-value-img {
					width: 100px;
					height: 100px;
					border-radius: var(--el-border-radius-circle);
					margin: auto;
				}
				.cropper-size {
					width: 50px;
					height: 50px;
				}
			}
			.cropper-warp-right-label {
				text-align: center;
				font-size: 12px;
				color: var(--el-text-color-primary);
				height: 30px;
				line-height: 30px;
			}
		}
	}
}
</style>
